package com.example.aidocengine.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.aidocengine.common.constant.BusinessConstant;
import com.example.aidocengine.common.exception.BusinessException;
import com.example.aidocengine.common.result.ResultCode;
import com.example.aidocengine.common.utils.FileUtils;
import com.example.aidocengine.mapper.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.aidocengine.pojo.dto.response.ValidationResultResponse;
import com.example.aidocengine.pojo.entity.*;
import com.example.aidocengine.pojo.vo.TerminologyValidationVO;
import com.example.aidocengine.processor.WordProcessor;
import com.example.aidocengine.processor.WordDocumentProcessor;
import com.example.aidocengine.service.StartupPlanValidationService;
import com.example.aidocengine.validator.PrimaryDeviceValidator;
import com.example.aidocengine.validator.SecondaryDeviceValidator;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@Service
public class StartupPlanValidationServiceImpl implements StartupPlanValidationService {

    @Autowired
    private WordProcessor wordProcessor;

    @Autowired
    private WordDocumentProcessor wordDocumentProcessor;

    @Autowired
    private SecondaryDeviceValidator secondaryDeviceValidator;

    @Autowired
    private PrimaryDeviceValidator primaryDeviceValidator;
    
    @Autowired
    private com.example.aidocengine.validator.AdvancedPrimaryDeviceValidator advancedPrimaryDeviceValidator;

    @Autowired
    private StartupPlanDocumentMapper startupPlanDocumentMapper;

    @Autowired
    private OperationStepValidationMapper operationStepValidationMapper;

    @Autowired
    private CommandingUnitMapper commandingUnitMapper;
    
    // 设备信息查询（用于校验设备双编是否存在于模板）
    @Autowired
    private com.example.aidocengine.mapper.DeviceInfoMapper deviceInfoMapper;
    
    @Autowired
    private StartupPlanValidationStatisticsMapper statisticsMapper;

    @Value("${file.upload.startup-plan}")
    private String startupPlanDir;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ValidationResultResponse validateStartupPlan(MultipartFile file, String description) {
        log.info("开始校验启动方案文档，文件名：{}", file.getOriginalFilename());

        // 验证文件
        if (!FileUtils.isValidFile(file)) {
            throw new BusinessException(ResultCode.FILE_UPLOAD_ERROR.getCode(), "无效的文件格式或文件为空");
        }

        if (!FileUtils.isWordFile(file.getOriginalFilename())) {
            throw new BusinessException(ResultCode.FILE_UPLOAD_ERROR.getCode(), "只支持Word文档格式(.docx, .doc)");
        }

        // 创建文档记录
        StartupPlanDocument document = new StartupPlanDocument();
        document.setTitle(description != null ? description : "启动方案校验");
        document.setFileName(file.getOriginalFilename());
        document.setFileSize(file.getSize());
        document.setUploadTime(LocalDateTime.now());
        document.setProcessStatus(0); // 0:未处理
        document.setValidationStatus(1); // 1:校验中

        startupPlanDocumentMapper.insert(document);

        try {
            // 先解析Word文档，提取文本和设备信息（在文件保存前）
            Map<String, Object> parseResult = wordDocumentProcessor.parseStartupPlan(file);
            
            // 解析成功后再保存文件
            String filePath = FileUtils.saveFile(file, startupPlanDir);
            document.setFilePath(filePath);
            
            // 立即更新文档记录以保存文件路径
            startupPlanDocumentMapper.updateById(document);
            
            @SuppressWarnings("unchecked")
            List<WordDocumentProcessor.OperationStepData> operationSteps = (List<WordDocumentProcessor.OperationStepData>) parseResult.get("operationSteps");
            @SuppressWarnings("unchecked")
            Set<String> deviceNames = (Set<String>) parseResult.get("deviceNames");
            @SuppressWarnings("unchecked")
            Set<String> voltageLevels = (Set<String>) parseResult.get("voltageLevels");
            Boolean foundSection7 = (Boolean) parseResult.get("foundSection7");
            
            if (operationSteps.isEmpty()) {
                if (!foundSection7) {
                    throw new BusinessException(ResultCode.DOCUMENT_PARSE_ERROR.getCode(), 
                        "未找到第七部分：启动前有关厂站一、二次设备运行方式调整及状态确认");
                } else {
                    throw new BusinessException(ResultCode.DOCUMENT_PARSE_ERROR.getCode(), 
                        "第七部分中未找到操作步骤表格数据");
                }
            }

            // 校验操作步骤 - 按照正确的统计方式逐行检查
            List<OperationStepValidation> validationResults = new ArrayList<>();

            int totalSteps = 0; // 总步骤数：每检查一行操作步骤，总步骤数+1
            int failedSteps = 0; // 未通过数：每一行校验未通过，未通过数+1

            log.info("开始逐行校验操作步骤，从标准操作表格中提取的行数：{}", operationSteps.size());
            log.info("正确的统计方式：从头到尾读取文件，读到表头为'序号，受令单位，操作步骤，发令人，发令时间，操作人，完成时间，备注'的表格，然后读取这些表格的每一行数据");

            // 逐条校验每一行操作步骤
            for (WordDocumentProcessor.OperationStepData stepData : operationSteps) {
                // 每检查一行，总步骤数+1
                totalSteps++;

                log.info("正在校验第{}行：受令单位={}, 操作步骤={}",
                    totalSteps, stepData.getCommandingUnit(),
                    stepData.getOperationStep().length() > 30 ?
                    stepData.getOperationStep().substring(0, 30) + "..." : stepData.getOperationStep());

                // 校验这一行（按照流程：1.受令单位 → 2.二次设备术语 → 3.一次设备术语）
                OperationStepValidation validation = validateOperationStep(document.getId(), stepData);
                validation.setTableIndex(stepData.getTableIndex());
                validation.setRowIndex(stepData.getRowIndex());
                validation.setCommanderColumnIndex(stepData.getCommanderColumnIndex());
                validationResults.add(validation);

                // 如果这一行校验未通过，未通过数+1
                if (!Boolean.TRUE.equals(validation.getIsValid())) {
                    failedSteps++;
                    log.info("❌ 第{}行校验未通过，错误信息：{}，当前统计 -> 总步骤数：{}，未通过数：{}",
                            totalSteps, validation.getErrorMessage(), totalSteps, failedSteps);
                } else {
                    log.info("✅ 第{}行校验通过，当前统计 -> 总步骤数：{}，未通过数：{}", totalSteps, totalSteps, failedSteps);
                }
            }
            
            // 计算通过数量 = 总步骤数 - 未通过数
            int passedSteps = totalSteps - failedSteps;
            
            // 计算最大序号用于统计记录
            int maxSequenceNumber = calculateTotalStepsFromSequence(operationSteps);
            
            log.info("校验完成统计：总步骤数={}, 未通过数={}, 通过数={}, 文档最大序号={}", 
                totalSteps, failedSteps, passedSteps, maxSequenceNumber);

            // 批量保存校验结果
            if (!validationResults.isEmpty()) {
                operationStepValidationMapper.insertBatch(validationResults);
            }

            // 更新文档处理状态
            // 将校验结果存储为JSON格式
            String resultJson = String.format("{\"totalSteps\":%d,\"passedSteps\":%d,\"failedSteps\":%d}", 
                    totalSteps, passedSteps, failedSteps);
            document.setValidationResult(resultJson);
            document.setProcessStatus(2); // 2:处理完成
            document.setValidationStatus(2); // 2:校验完成
            startupPlanDocumentMapper.updateById(document);

            log.info("启动方案校验完成，总步骤数：{}, 通过：{}, 失败：{}", totalSteps, passedSteps, failedSteps);

            // 保存校验统计数据
            saveValidationStatistics(document.getId(), totalSteps, passedSteps, failedSteps, maxSequenceNumber);

            // 构造返回结果
            return buildValidationResponse(document, validationResults, totalSteps, passedSteps, failedSteps);

        } catch (Exception e) {
            log.error("启动方案校验失败：", e);
            
            // 更新文档状态为失败
            document.setProcessStatus(3); // 3:处理失败
            document.setValidationStatus(3); // 3:校验失败
            startupPlanDocumentMapper.updateById(document);

            throw new BusinessException(ResultCode.STARTUP_PLAN_VALIDATION_ERROR.getCode(), 
                "启动方案校验失败：" + e.getMessage());
        }
    }

    /**
     * 校验单个操作步骤
     * 按照正确的流程：1.受令单位校验 → 2.二次设备术语检查 → 3.一次设备术语检查（设备模板+编写原则）
     */
    private OperationStepValidation validateOperationStep(Long documentId, WordDocumentProcessor.OperationStepData stepData) {
        OperationStepValidation validation = new OperationStepValidation();
        validation.setDocumentId(documentId);
        validation.setOperationStep(stepData.getOperationStep());
        validation.setValidationTime(LocalDateTime.now());

        try {
            String commandingUnit = stepData.getCommandingUnit();
            String operationStep = stepData.getOperationStep();

            log.debug("开始校验操作步骤：受令单位={}, 操作步骤={}", commandingUnit,
                     operationStep.length() > 50 ? operationStep.substring(0, 50) + "..." : operationStep);

            // 第一步：校验受令单位
            if (!validateCommandingUnit(commandingUnit)) {
                validation.setIsValid(false);
                validation.setErrorMessage("该受令单元不存在");
                log.debug("受令单位校验失败：{}", commandingUnit);
                return validation;
            }
            log.debug("受令单位校验通过：{}", commandingUnit);

            // 第二步：二次设备术语检查
            // 扫描操作步骤是否包含术语库中的关键字，未命中时不用填写提示，直接进入一次设备术语检查
            TerminologyValidationVO secondaryValidation = secondaryDeviceValidator.validateSecondaryDeviceTerminology(operationStep);

            if (secondaryValidation.getIsValid()) {
                // 二次设备术语检查通过，校验完成
                validation.setIsValid(true);
                log.debug("操作步骤通过二次设备术语检查：{}", operationStep);
                return validation;
            }

            log.debug("二次设备术语未命中，进入一次设备术语检查");

            // 第三步：一次设备术语检查
            // 首先判断操作步骤中括号内容（设备双编）是否属于设备模板
            String deviceTemplate = extractDeviceTemplate(operationStep);
            if (deviceTemplate != null && !isValidDeviceTemplateByDB(deviceTemplate, stepData.getCommandingUnit(), operationStep)) {
                validation.setIsValid(false);
                validation.setErrorMessage("该一次设备命名不规范");
                log.debug("设备模板校验失败：{}", deviceTemplate);
                return validation;
            }

            // 然后判断操作步骤是否符合一次设备编写原则，并且还要符合特殊说明
            TerminologyValidationVO primaryValidation = validatePrimaryDeviceWritingPrinciple(operationStep);

            if (!primaryValidation.getIsValid()) {
                validation.setIsValid(false);
                validation.setErrorMessage("不符合一次设备编写原则");
                log.debug("一次设备编写原则校验失败：{}, 原因：{}", operationStep, primaryValidation.getErrorMessage());
                return validation;
            }

            // 所有校验都通过
            validation.setIsValid(true);
            log.debug("操作步骤校验全部通过");

        } catch (Exception e) {
            log.error("校验操作步骤异常：{}", stepData.getOperationStep(), e);
            validation.setIsValid(false);
            validation.setErrorMessage("校验异常：" + e.getMessage());
        }

        return validation;
    }

    /**
     * 使用设备信息表验证设备双编是否存在
     */
    private boolean isValidDeviceTemplateByDB(String deviceTemplate, String commandingUnit, String operationStep) {
        if (!org.springframework.util.StringUtils.hasText(deviceTemplate)) {
            return true;
        }
        String doubleCode = deviceTemplate.trim();
        String stationName = org.springframework.util.StringUtils.hasText(commandingUnit) ? normalizeStationName(commandingUnit.trim()) : null;
        String voltageLevel = null;
        try {
            // 从操作步骤中提取电压等级（如 220kV/110kV）
            java.util.regex.Pattern vp = java.util.regex.Pattern.compile("(\\d+(?:\\.\\d+)?kV)", java.util.regex.Pattern.CASE_INSENSITIVE);
            java.util.regex.Matcher vm = vp.matcher(operationStep != null ? operationStep : "");
            if (vm.find()) {
                voltageLevel = vm.group(1);
            }

            com.example.aidocengine.pojo.entity.DeviceInfo deviceInfo =
                deviceInfoMapper.selectByDoubleCodeWithContext(doubleCode, stationName, voltageLevel);
            if (deviceInfo == null) {
                // 回落到仅按双编匹配（兼容缺失上下文的情况）
                deviceInfo = deviceInfoMapper.selectByDeviceDoubleCode(doubleCode);
            }
            boolean exists = deviceInfo != null;
            log.debug("设备双编存在性校验：doubleCode={}, station={}, voltage={}, 命中={}",
                    doubleCode, stationName, voltageLevel, exists);
            return exists;
        } catch (Exception e) {
            log.warn("校验设备双编异常：{}", e.getMessage());
            return false;
        }
    }

    /**
     * 根据序号计算总步骤数 - 找到最后一条操作步骤的序号
     */
    private int calculateTotalStepsFromSequence(List<WordDocumentProcessor.OperationStepData> operationSteps) {
        int maxSequence = 0;
        int validSequenceCount = 0;
        
        log.info("开始分析序号，总共解析出{}个步骤", operationSteps.size());
        
        for (WordDocumentProcessor.OperationStepData stepData : operationSteps) {
            String sequenceStr = stepData.getSequenceNumber();
            if (sequenceStr != null && !sequenceStr.trim().isEmpty()) {
                try {
                    // 跳过行号形式的序号（这些是我们为空序号行生成的）
                    if (sequenceStr.matches("^\\d{1,2}$")) {
                        int rowNumber = Integer.parseInt(sequenceStr);
                        if (rowNumber < 100) { // 跳过可能的行号
                            continue;
                        }
                    }
                    
                    String cleanStr = sequenceStr.trim();
                    
                    // 匹配格式：纯数字、数字.、数字、等
                    if (cleanStr.matches("^\\d+[、。\\.]?$")) {
                        String numberPart = cleanStr.replaceAll("[^0-9]", "");
                        if (!numberPart.isEmpty()) {
                            int sequence = Integer.parseInt(numberPart);
                            // 接受所有正数序号，找到最大值作为总步骤数
                            if (sequence > 0 && sequence <= 1000) {
                                maxSequence = Math.max(maxSequence, sequence);
                                validSequenceCount++;
                                log.debug("发现序号：{} -> {}", sequenceStr, sequence);
                            }
                        }
                    }
                } catch (NumberFormatException e) {
                    log.debug("解析序号失败：'{}'", sequenceStr);
                }
            }
        }
        
        log.info("序号分析结果：最后一条操作步骤序号={}，有效序号数量={}，解析步骤总数={}", maxSequence, validSequenceCount, operationSteps.size());
        
        // 如果没有找到有效序号，使用解析出的步骤数量
        if (maxSequence == 0) {
            maxSequence = operationSteps.size();
            log.warn("未找到有效序号，使用解析步骤数：{}", maxSequence);
        }
        
        log.info("确定总步骤数：{}（基于文档中最后一条操作步骤的序号）", maxSequence);
        return maxSequence;
    }

    /**
     * 从校验结果中计算总步骤数（用于getValidationResult方法）
     */
    private int calculateTotalStepsFromValidationResults(List<OperationStepValidation> validationResults) {
        // 由于OperationStepValidation实体中没有序号信息，
        // 暂时使用解析出的步骤数作为总步骤数
        // TODO: 后续可以考虑从document的validation_result JSON字段中读取totalSteps
        return validationResults.size();
    }

    /**
     * 校验受令单位是否存在
     */
    private boolean validateCommandingUnit(String commandingUnitName) {
        if (!StringUtils.hasText(commandingUnitName)) {
            log.debug("受令单位为空，校验失败");
            return false;
        }

        String original = commandingUnitName.trim();
        // 1) 精确匹配
        QueryWrapper<CommandingUnit> wrapper = new QueryWrapper<>();
        wrapper.eq("unit_name", original).eq("status", 1);
        CommandingUnit unit = commandingUnitMapper.selectOne(wrapper);
        if (unit != null) {
            log.debug("校验受令单位（精确）：{} -> 存在", original);
            return true;
        }

        // 2) 规范化名称后模糊匹配（去除常见后缀/空白/括号内内容）
        String normalized = normalizeStationName(original);
        if (StringUtils.hasText(normalized)) {
            QueryWrapper<CommandingUnit> likeWrapper = new QueryWrapper<>();
            likeWrapper.like("unit_name", normalized).eq("status", 1);
            CommandingUnit likeHit = commandingUnitMapper.selectOne(likeWrapper);
            if (likeHit != null) {
                log.debug("校验受令单位（模糊）：{} | {} -> 命中:{}", original, normalized, likeHit.getUnitName());
                return true;
            }
        }

        log.debug("校验受令单位：{}，结果：不存在", original);
        return false;
    }

    /**
     * 站名归一化：去掉空白、常见后缀、括号内容
     */
    private String normalizeStationName(String name) {
        if (!StringUtils.hasText(name)) return null;
        String s = name;
        // 去除括号及其内容
        s = s.replaceAll("（[^）]*）", "").replaceAll("\u0028[^\u0029]*\u0029", ""); // 中文/英文括号
        // 移除空白
        s = s.replaceAll("\\s+", "");
        // 去常见后缀
        String[] suffixes = {"变电站", "开关站", "供电公司", "供电局", "变电所", "变电", "开关所", "站", "所"};
        for (String suf : suffixes) {
            if (s.endsWith(suf)) {
                s = s.substring(0, s.length() - suf.length());
                break;
            }
        }
        return s;
    }

    /**
     * 从操作步骤中提取设备双编（括号内容）
     */
    private String extractDeviceTemplate(String operationStep) {
        if (!StringUtils.hasText(operationStep)) {
            return null;
        }

        // 使用正则表达式提取括号内的内容，这通常是设备双编
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("\\(([^)]+)\\)|（([^）]+)）");
        java.util.regex.Matcher matcher = pattern.matcher(operationStep);

        if (matcher.find()) {
            // 返回第一个匹配的括号内容
            String content = matcher.group(1) != null ? matcher.group(1) : matcher.group(2);
            log.debug("从操作步骤中提取设备双编：{}", content);
            return content.trim();
        }

        return null;
    }

    /**
     * 校验设备双编是否符合设备模板
     */
    private boolean isValidDeviceTemplate(String deviceTemplate) {
        if (!StringUtils.hasText(deviceTemplate)) {
            return true; // 没有设备双编时不进行此项校验
        }

        // TODO: 这里应该查询设备模板表，判断设备双编是否符合规范
        // 暂时使用简单的规则：设备双编应该包含字母和数字的组合
        // 实际实现时应该查询数据库中的设备模板配置

        // 简单校验：设备双编应该不为空且长度大于2
        if (deviceTemplate.length() < 2) {
            log.debug("设备双编过短：{}", deviceTemplate);
            return false;
        }

        // 可以添加更多的设备命名规范检查
        // 例如：检查是否符合特定的命名模式等

        log.debug("设备双编校验通过：{}", deviceTemplate);
        return true;
    }

    /**
     * 校验一次设备编写原则和特殊说明
     */
    private TerminologyValidationVO validatePrimaryDeviceWritingPrinciple(String operationStep) {
        TerminologyValidationVO result = new TerminologyValidationVO();

        try {
            // 使用高级校验器进行更精确的校验
            result = advancedPrimaryDeviceValidator.validateWithTemplate(operationStep);
            log.debug("使用高级校验器进行一次设备编写原则校验");
        } catch (Exception e) {
            // 高级校验器异常时回退到基础校验器
            log.warn("高级校验器异常，回退到基础校验器：{}", e.getMessage());
            result = primaryDeviceValidator.validatePrimaryDeviceTerminology(operationStep);
        }

        return result;
    }

    /**
     * 构造校验结果响应
     */
    private ValidationResultResponse buildValidationResponse(StartupPlanDocument document,
                                                           List<OperationStepValidation> validationResults,
                                                           int totalSteps, int passedSteps, int failedSteps) {
        ValidationResultResponse response = new ValidationResultResponse();
        response.setDocumentId(document.getId());
        response.setDocumentName(document.getTitle());
        response.setValidationStatus(document.getValidationStatus().toString());
        response.setTotalSteps(totalSteps);
        response.setPassedSteps(passedSteps);
        response.setFailedSteps(failedSteps);

        // 构造详细校验结果
        List<ValidationResultResponse.ValidationDetailResponse> details = new ArrayList<>();
        for (OperationStepValidation validation : validationResults) {
            ValidationResultResponse.ValidationDetailResponse detail = new ValidationResultResponse.ValidationDetailResponse();
            detail.setOperationStep(validation.getOperationStep());
            detail.setValidationResult(Boolean.TRUE.equals(validation.getIsValid()) ? "PASS" : "FAIL");
            detail.setErrorMessage(validation.getErrorMessage());
            details.add(detail);
        }
        response.setValidationDetails(details);

        return response;
    }

    @Override
    public ValidationResultResponse getValidationResult(Long documentId) {
        StartupPlanDocument document = startupPlanDocumentMapper.selectById(documentId);
        if (document == null) {
            throw new BusinessException(ResultCode.NOT_FOUND.getCode(), "文档不存在");
        }

        List<OperationStepValidation> validationResults = operationStepValidationMapper.selectByDocumentId(documentId);

        // 从数据库记录中重新计算，保持与validateStartupPlan方法一致
        if (validationResults.isEmpty()) {
            // 如果没有校验记录，返回默认值
            return buildValidationResponse(document, validationResults, 0, 0, 0);
        }
        
        // 统计总操作数 = 校验结果数量
        int totalSteps = validationResults.size();
        
        // 统计未通过数量
        int failedSteps = (int) validationResults.stream()
                .filter(v -> !Boolean.TRUE.equals(v.getIsValid()))
                .count();
        
        // 计算通过数量
        int passedSteps = totalSteps - failedSteps;
        
        log.info("getValidationResult统计：总操作数={}, 未通过数={}, 通过数={}", totalSteps, failedSteps, passedSteps);

        return buildValidationResponse(document, validationResults, totalSteps, passedSteps, failedSteps);
    }

    @Override
    public byte[] generateModifiedWordDocument(Long documentId) {
        log.info("开始生成修改后的Word文档，文档ID：{}", documentId);
        
        // 获取文档信息
        StartupPlanDocument document = startupPlanDocumentMapper.selectById(documentId);
        if (document == null) {
            throw new BusinessException(ResultCode.NOT_FOUND.getCode(), "文档不存在");
        }
        
        // 获取校验结果
        List<OperationStepValidation> validationResults = operationStepValidationMapper.selectByDocumentId(documentId);
        if (validationResults.isEmpty()) {
            throw new BusinessException(ResultCode.NOT_FOUND.getCode(), "校验结果不存在");
        }
        
        try {
            // 加载原始Word文档
            XWPFDocument wordDocument = wordDocumentProcessor.loadWordDocument(document.getFilePath());
            
            // 将校验结果转换为WordDocumentProcessor所需的格式
            List<WordDocumentProcessor.ValidationResultDetail> resultDetails = new ArrayList<>();
            for (OperationStepValidation validation : validationResults) {
                WordDocumentProcessor.ValidationResultDetail detail = new WordDocumentProcessor.ValidationResultDetail();
                detail.setPassed(Boolean.TRUE.equals(validation.getIsValid()));
                detail.setErrorMessage(validation.getErrorMessage());
                detail.setOperationStep(validation.getOperationStep());
                // 使用保存的位置信息
                detail.setTableIndex(validation.getTableIndex());
                detail.setRowIndex(validation.getRowIndex());
                detail.setCommanderColumnIndex(validation.getCommanderColumnIndex());
                resultDetails.add(detail);
            }
            
            // 处理校验结果，在失败的行添加错误信息
            wordDocumentProcessor.processValidationResults(wordDocument, resultDetails);
            
            // 保存修改后的文档为字节数组
            byte[] modifiedDocument = wordDocumentProcessor.saveModifiedDocument(wordDocument);
            
            log.info("修改后的Word文档生成完成，大小：{} bytes", modifiedDocument.length);
            return modifiedDocument;
            
        } catch (Exception e) {
            log.error("生成修改后的Word文档失败：", e);
            throw new BusinessException(ResultCode.STARTUP_PLAN_VALIDATION_ERROR.getCode(), 
                "生成修改后的Word文档失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存校验统计数据
     */
    private void saveValidationStatistics(Long documentId, int totalSteps, int passedSteps, int failedSteps, int maxSequenceNumber) {
        try {
            // 先检查是否已存在该文档的统计记录
            LambdaQueryWrapper<StartupPlanValidationStatistics> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StartupPlanValidationStatistics::getDocumentId, documentId);
            StartupPlanValidationStatistics existing = statisticsMapper.selectOne(queryWrapper);
            
            if (existing != null) {
                // 更新现有记录
                existing.setTotalSteps(totalSteps);
                existing.setPassedSteps(passedSteps);
                existing.setFailedSteps(failedSteps);
                existing.setMaxSequenceNumber(maxSequenceNumber);
                existing.setUpdatedTime(LocalDateTime.now());
                statisticsMapper.updateById(existing);
                log.info("更新校验统计数据：文档ID={}, 总步骤={}, 通过={}, 失败={}", documentId, totalSteps, passedSteps, failedSteps);
            } else {
                // 创建新记录
                StartupPlanValidationStatistics statistics = new StartupPlanValidationStatistics();
                statistics.setDocumentId(documentId);
                statistics.setTotalSteps(totalSteps);
                statistics.setPassedSteps(passedSteps);
                statistics.setFailedSteps(failedSteps);
                statistics.setMaxSequenceNumber(maxSequenceNumber);
                statistics.setCreatedTime(LocalDateTime.now());
                statistics.setUpdatedTime(LocalDateTime.now());
                statisticsMapper.insert(statistics);
                log.info("保存校验统计数据：文档ID={}, 总步骤={}, 通过={}, 失败={}", documentId, totalSteps, passedSteps, failedSteps);
            }
        } catch (Exception e) {
            log.error("保存校验统计数据失败：", e);
            // 不抛出异常，避免影响主要的校验流程
        }
    }
    
    @Override
    public StartupPlanValidationStatistics getLatestValidationStatistics() {
        try {
            // 查询最新的校验统计记录（按创建时间倒序）
            LambdaQueryWrapper<StartupPlanValidationStatistics> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.orderByDesc(StartupPlanValidationStatistics::getCreatedTime);
            queryWrapper.last("LIMIT 1");
            
            StartupPlanValidationStatistics statistics = statisticsMapper.selectOne(queryWrapper);
            
            if (statistics == null) {
                // 如果没有统计记录，返回默认值
                statistics = new StartupPlanValidationStatistics();
                statistics.setTotalSteps(0);
                statistics.setPassedSteps(0);
                statistics.setFailedSteps(0);
                statistics.setMaxSequenceNumber(0);
            }
            
            log.info("获取最新校验统计数据：总步骤={}, 通过={}, 失败={}", 
                statistics.getTotalSteps(), statistics.getPassedSteps(), statistics.getFailedSteps());
            
            return statistics;
        } catch (Exception e) {
            log.error("获取最新校验统计数据失败：", e);
            // 返回默认值
            StartupPlanValidationStatistics defaultStats = new StartupPlanValidationStatistics();
            defaultStats.setTotalSteps(0);
            defaultStats.setPassedSteps(0);
            defaultStats.setFailedSteps(0);
            defaultStats.setMaxSequenceNumber(0);
            return defaultStats;
        }
    }
}
